package com.posjiajia.user.core.bo;

import com.posjiajia.user.core.dao.DeviceDao;
import com.posjiajia.user.core.dao.OrganDao;
import com.posjiajia.user.core.params.DeviceQueryParam;
import com.posjiajia.user.core.po.DevicePo;
import com.posjiajia.user.core.po.OrganPo;
import com.posjiajia.user.core.utils.BeanTransferUtil;
import com.posjiajia.user.core.vo.DeviceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhenhua.sun
 * @title com.posjiajia.user.core.bo
 * @date 9/25/16
 */
@Service
public class DeviceBo {

    @Autowired
    private DeviceDao deviceDao;

    @Autowired
    private OrganDao organDao;

    @Autowired
    private SequenceBo sequenceBo;

    public void update(DeviceVo deviceVo) {
        DevicePo po = BeanTransferUtil.transferType(deviceVo,DevicePo.class);
        deviceDao.update(po);
    }

    public void insert(DeviceVo deviceVo) {
        DevicePo po = BeanTransferUtil.transferType(deviceVo,DevicePo.class);
        po.setDeviceId(sequenceBo.getNextDeviceId());
        deviceDao.insert(po);
    }

    public DevicePo selectByKey(Long deviceId){
        return deviceDao.selectByKey(deviceId);
    }

    public DevicePo selectByMac(String mac){
        return deviceDao.selectByMac(mac);
    }

    public List<DeviceVo> query(DeviceQueryParam deviceQueryParam) {
        DevicePo poParam = BeanTransferUtil.transferType(deviceQueryParam, DevicePo.class);
        List<DevicePo> poList = deviceDao.selectList(poParam);
        List<DeviceVo> voList = BeanTransferUtil.batchTransferType(poList,DeviceVo.class);
        for (DeviceVo vo : voList){
            if (vo.getBaseOrganId() != null) {
                OrganPo baseOrgan = getOrgan(vo.getBaseOrganId());
                vo.setBaseOrganName(baseOrgan == null ? "" : baseOrgan.getName());
            }
            if (vo.getTopOrganId() != null) {
                OrganPo topOrgan = getOrgan(vo.getTopOrganId());
                vo.setTopOrganName(topOrgan == null ? "" : topOrgan.getName());
            }
        }
        return voList;
    }

    public OrganPo getOrgan(Long organId){
        return organDao.queryByOrganId(Integer.parseInt(String.valueOf(organId)));
    }
}
